<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Zhifa;
use think\Config;
use think\Cache;
use think\Db;
use think\Validate;
use app\api\common\Program;


class Login extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 小程序授权登录
     * @path api/login/xcxLogin
     * @param string $code
     * */
    public function Login()
    {
        $tel = $this->request->param('tel');
        $password = $this->request->param("password");
        if(empty($tel))
        {
            $this->error('请输入账号');
        } 
        if(empty($password))
        {
            $this->error('请输入密码');
        } 
        $info = Zhifa::login($tel,$password);
        if(empty($info))
        {
            $this->error('账号不存在');
        }
        if(md5($password)!=$info->password)
        {
            $this->error('密码不正确');
        }
        if ($info->is_jin == 1){
            $this->error('您的账号已被禁用,请联系管理员');
        }
        if ($info) {
            $this->auth->smallLogin($info->id,1);
            $data = ['userinfo' => $this->auth->getUserinfo(1)];
            
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
        
    }

    function forget()
    {
        $mobile = $this->request->post("tel");
        $code = $this->request->post("code");
        $password = $this->request->post('password');
        $c_password = $this->request->post('repassword');
        if (!$mobile) {
            $this->error('手机号不能为空');
        }
        $info = Zhifa::where(["tel"=>$mobile,"is_del"=>'0'])->find();
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号有误');
        }
        if(!$info){
            $this->error('账号不存在,请先注册');
        }
        $name = 'forget_'.$mobile;
        $yzm = Cache::get($name);
        if(empty($yzm) || $yzm == false){
            $this->error("请先发送验证码");
        }
        if(!$code){
            $this->error("验证码不能为空");
        }
        if($yzm!=$code){
            $this->error('验证码有误');
        }
        if (!$password) {
            $this->error('密码不能为空');
        }
        if (!$c_password) {
            $this->error('确认密码不能为空');
        }
        if($password != $c_password){
            $this->error('两次密码不一致');
        }
        $ret = Zhifa::where(["tel"=>$mobile,"is_del"=>'0'])->update(['password'=>md5($password)]);
        if ($ret!==false) {
            $this->success('修改成功');
        } else {
            $this->error($this->auth->getError());
        }
    }
    function logout()
    {
        $result=$this->auth->logout();
        if($result)
        {
            $this->success('退出成功');
        }
        else
        {
            $this->error('已退出登录');
        }
    }


}
